# -*- coding: utf-8 -*-
# @Time    : 2022/10/10 22:19
# @Author  : 修远
# @File    : user.py
# @Comment : 
from app.libs.redprint import Redprint
from app.model.User import User
from app.model.Result import Result
from app.model.Student import Student
from flask import jsonify, request, current_app
from flask_login import login_user
from app.validators.forms import LoginForm
from app.utils.enums import Status
from app.utils.TokenUtils import create_token, verify_token
from app.utils.RedisUtils import set_redis_data, get_redis_data
from flask_login import current_user
from app.utils.celeryUtils import save_act_history, add

api = Redprint('user')


@api.route("/index", methods=["GET"])
def index():
    try:
        result = Result(Status.SUCCESS_CODE.value, Status.SUCCESS.value)
        user = User.query.all()
        result.result["data"] = []
        for u in user:
            student = Student()
            student.id = u.id
            student.name = u.username
            student.email = u.email
            student.logintime = u.logintime
            result.result["data"].append(student)
        return jsonify(result)
    except Exception as e:
        result = Result(Status.FAIL_CODE.value, Status.FAIL.value)
        result.result = e.args
        return jsonify(result)


@api.route("/login", methods=["POST"])
def login():
    try:
        form = LoginForm(request.form)
        if form.validate():
            user = User.query.filter_by(email=form.email.data).first()
            if user and user.check_password(form.password.data):
                result = Result(Status.SUCCESS_CODE.value, Status.SUCCESS.value, None)
                # 设置token
                token = create_token(user.id, user.username, user.email, form.password.data)
                set_redis_data(user.id, token)  # 存储token到redis
                save_act_history.apply_async(args=[user.id, Status.LOGIN_SUCCESS.value,
                                                   "用户登录IP地址：" + str(request.remote_addr)],
                                             countdown=current_app.config["COUNTDOWN"])

                # task = add.delay(1, 2)
                login_user(user, remember=True)
                return jsonify(result)
            result = Result(Status.SUCCESS_CODE.value, Status.USER_OR_PASSWORD_NO.value)
            return jsonify(result)
        result = Result(Status.FAIL_CODE.value, Status.FAIL.value)
        if form.email.errors:
            email_error = [i for i in form.email.errors]
            result.result["emailError"] = email_error
        if form.password.errors:
            password_error = [i for i in form.password.errors]
            result.result["passwordError"] = password_error
        return jsonify(result)
    except Exception as e:
        result = Result(Status.FAIL_CODE.value, str(e.args), None)
        return jsonify(result)


@api.route("/getToken", methods=["POST"])
def getToken():
    try:
        form = request.form
        user = User.query.filter_by(email=form["email"]).first()
        # 设置token
        token = create_token(user.id, user.username, user.email, form["password"])
        result = Result(Status.SUCCESS_CODE.value, Status.SUCCESS.value)
        result.result["token"] = token
        return jsonify(result)
    except Exception as e:
        result = Result(Status.FAIL_CODE.value, str(e.args), None)
        return jsonify(result)


@api.route("/verifyToken", methods=["POST"])
def verifyToken():
    try:
        form = request.headers.get("Authorization")
        data = verify_token(form)
        result = Result(Status.SUCCESS_CODE.value, Status.SUCCESS.value)
        result.result["data"] = data
        return jsonify(result)
    except Exception as e:
        result = Result(Status.FAIL_CODE.value, str(e.args), None)
        return jsonify(result)


@api.route("/getRedisToken", methods=["GET"])
def getRedisToken():
    try:
        token = get_redis_data(current_user.id)
        data = verify_token(token)
        result = Result(Status.SUCCESS_CODE.value, Status.SUCCESS.value)
        result.result["data"] = data
        return jsonify(result)
    except Exception as e:
        result = Result(Status.FAIL_CODE.value, str(e.args), None)
        return jsonify(result)
